<?php

namespace App\Http\Controllers\Admin\ExportList;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Admin\SampleInfo;
use App\Http\Controllers\Admin\SampleInfoController;
use QrCode;


class ShanXiShiJiZhongShiController extends Controller
{

    /* 试验台账 导出Excel */
    public function export($request, $search) {
        @set_time_limit(0);
        ini_set('max_execution_time', 0);
        ini_set('memory_limit', "-1");
        $para = $request->get('params');
        $para = json_decode($para, true);
        $para['is_search'] = $search;
        $sampleCon = new SampleInfoController();
        $data = $sampleCon->listData($para);
        if(is_string($data)) {
            return $data;
        }
        $total = $data['iTotalDisplayRecords'];
        if($total === 0) {
            return '内容为空';
        }
        $data = $data['data'];
        $template_file = './storage/ExcelTemplate/ShanXiShiJiZhongShi/检测台账.xls'; //考虑到兼容Linux，斜杠用“/”
        if(!file_exists($template_file)) {
            return '模板文件不存在';
        }
        $report_num_pre = DB::table('setting')->where('id', '1')->value('report_num_pre');                                                             //报告编号前缀
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($template_file);                                                                      //读取模板文件
        $sheet = $spreadsheet->getSheet(0);                                                                                               //按索引获取表单，从 0 开始
        $domain = $request->server('HTTP_HOST');                                                                                                       //域名
        $rowIndex_sam_info = 3;                                                                                                                        //样品信息的行号
        $qr_code_path = [];

        foreach($data as $kk => $vv) {
            $sheet->getRowDimension($rowIndex_sam_info)->setRowHeight(75);
            $time = strtotime($vv->ctime);
            $month = date('m', $time);
            $day = date('d', $time);
            $rowData = [
                $kk + 1, //序号
                date('Y', $time), //年度
                $month.'月第'.ceil($day/7).'周', //周次
                $vv->place, //jia
                $vv->b_entrusted_company, //委托单位
                $vv->b_batchNum, //批次号
                $vv->bar_code, //条形码
                $vv->c_voltage, //额定电压（kV）
                $vv->c_tool_name, //物资名称
                $vv->e_name, //物资分类
                $vv->guige_xinghao, //物资型号
                $vv->c_class, //分类
                1, //试验数量
                $vv->c_unit, //计量单位
                $vv->self_num, //样品自编码
                $vv->brand, //样品自编码
                $vv->production_date, //生产日期
                $vv->manufacturer, //生产厂家
                $vv->c_std_num, //检测标准
                $vv->c_item_names, //试验项目
                $vv->test_time, //试验时间
                ($vv->res === 1 ? '合格' : ($vv->res === 0 ? '未检测' : '不合格')), //检测结果
                $vv->g_name, //不合格项目
                $vv->next_time, //有效期
                $report_num_pre.$vv->b_batchNum,  //报告编号
                'photo',
                'non_photo',
                'qr_code',
                ($vv->c_tool_id === 47 ? 8000 : 300), //检测费用（元）
                $vv->b_paid_at, //支付日期
                ($vv->b_paid_status === 1 ? '已支付' : '未支付'), //支付状态
                $vv->b_paid_num, //付款合同编号
                $vv->remark, //备注
                $vv->b_client_contact, //联系人
                $vv->b_client_tel,  //联系电话
            ];
            $rowheight = $sheet->getRowDimension($rowIndex_sam_info)->getRowHeight(); //行高
            foreach ($rowData as $i => $value) {
                $col = dec2ABC($i+1);
                switch ($value) {
                    case 'photo':
                        /* ---------------- 铭牌照片 -------------------- */
                            if(isset($request->export_photo)) {
                                $vv->photo = '.'.$vv->photo;
                                if(is_file($vv->photo)) {
                                    $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                                    $drawing->setPath($vv->photo);                       //图片的路径
                                    $drawing->setResizeProportional(false);              //不保持宽高比
                                    $drawing->setWidthAndHeight($rowheight, $rowheight); //高度
                                    $drawing->setOffsetX(5);
                                    $drawing->setOffsetY(5);
                                    $drawing->setCoordinates($col.$rowIndex_sam_info); //指定位置,名牌照片
                                    $drawing->setWorksheet($sheet);
                                }
                            }
                        /* ---------------- 铭牌照片end -------------------- */
                        break;
                    case 'non_photo':
                        /* ---------------- 不合格照片 -------------------- */
                            if(isset($request->export_nonphoto)) {
                                $vv->non_photo = '.'.$vv->non_photo;
                                if(is_file($vv->non_photo)) {
                                    $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                                    $drawing->setPath($vv->non_photo); //图片的路径
                                    $sheet->getCell("Z".$rowIndex_sam_info);
                                    $drawing->setResizeProportional(false);                    //不保持宽高比
                                    $drawing->setWidthAndHeight(1.3*$rowheight, $rowheight); //高度
                                    $drawing->setOffsetX(5);
                                    $drawing->setOffsetY(5);
                                    $drawing->setCoordinates('Z'.$rowIndex_sam_info); //指定位置,不合格照片
                                    $drawing->setWorksheet($sheet);
                                }
                            }
                        /* ---------------- 不合格照片end -------------------- */
                        break;
                    case 'qr_code':
                        /* ---------------- 二维码 -------------------- */
                            if(isset($request->export_erweima)) {
                                $key = $vv->key; //批次的密钥
                                $url_name = 'http://'.$domain."/viewRes?id={$vv->id}&k={$key}";
                                $qr_code_path[$kk] = "./QrCodeImage/viewResId{$vv->id}Key{$key}.png";
                                $qrCode = QrCode::format('png');
                                $qrCode = $qrCode->size(120);
                                $qrCode = $qrCode->margin(0);
                                if($qrCode->generate($url_name, $qr_code_path[$kk])) {
                                    $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                                    $drawing->setPath($qr_code_path[$kk]);               //图片的路径
                                    $drawing->setResizeProportional(false);              //不保持宽高比
                                    $drawing->setWidthAndHeight($rowheight, $rowheight); //高度
                                    $drawing->setOffsetX(5);
                                    $drawing->setOffsetY(5);
                                    $drawing->setCoordinates('AA'.$rowIndex_sam_info); //指定位置,二维码
                                    $drawing->setWorksheet($sheet);
                                }
                            }
                        /* ---------------- 二维码end -------------------- */
                        break;
                    
                    default:
                        $sheet->getCell($col.$rowIndex_sam_info)->setValue($value); 
                        break;
                }
            }
            $rowIndex_sam_info ++;
        }
        $styleArray = ['borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,]], 'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, 'wrapText' => TRUE,],];
        $max_col = isset($col) ? $col : 'AH';
        $sheet->getStyle('A1:'.$max_col.($rowIndex_sam_info - 1))->applyFromArray($styleArray);
        //----------直接在浏览器下载----start
        $today = date('Y-m-d');
        $outname = '近半年数据，下载时间：'.$today;
        if(isset($para['searcho'])) {
            $parao = array_column($para['searcho'], 'value', 'name');
            $danwei = $parao['b_entrusted_company'] ? '检测单位：'.$parao['b_entrusted_company'].'，' : '';
            $pici = $parao['b_batchNum'] ? '批次号：'.$parao['b_batchNum'].'，' : '';
            $startdate = $parao['test_time_0'];
            $enddate = $parao['test_time_1'];
            $date = '';
            if($startdate || $enddate) {
                $date .= '日期范围：';
                $date .= $enddate ? ($startdate ? $startdate : '').'至'.$enddate : ($startdate ? $startdate.'至'.$today : '');
                $date .= ',';
            }
            $outname = $danwei.$pici.$date.'下载时间：'.$today;
        }

        $file_name = "检测台账(".$outname.").xls";                                   //输出的文件名称
        // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出Excel 07文件
        header('Content-Type: application/vnd.ms-excel');                            //告诉浏览器输出Excel 03版本文件
        header('Content-Disposition: attachment;filename='.urlencode($file_name)); //告诉浏览器输出的文件名称
        header('Cache-Control: max-age=0');                                          //禁止缓存
        //----------直接在浏览器下载----end

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        $writer->setPreCalculateFormulas(false); //禁用公式预先计算
        $writer->save('php://output');           //直接在浏览器下载
        //为了防止内存泄露，建议用完手动清理
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        foreach($qr_code_path as $vv) {
            @unlink($vv);
        }
    }

}
